package com.xpresso.utils.unitTests;

import com.erclab.internal.xpresso.Application;
import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.dataAccess.ApplicationDataSource;
import com.erclab.internal.xpresso.exceptions.ApplicationException;
import com.xpresso.utils.email.EmailConfiguration;
import com.xpresso.utils.email.EmailMessage;
import com.xpresso.utils.email.queue.QueueCommand;
import com.xpresso.utils.email.queue.QueueConfiguration;
import com.xpresso.utils.email.queue.SimpleEmailQueueManager;
import com.xpresso.utils.exceptions.XpressoException;

import junit.framework.TestCase;

public class TestEmailQueue extends TestCase {

	protected SimpleEmailQueueManager qm;
	
	@Override
	public void setUp(){
		qm = new SimpleEmailQueueManager();
		QueueConfiguration config = new QueueConfiguration();
		ApplicationDataSource ads = null;
		try {
			@SuppressWarnings("unused")
			Application app = new Application();
			ads = Settings.getRepository().getApplicationDataSource(2);  // 2 is the id of the xpresso_data datasource
		} catch (ApplicationException e) {
			e.printStackTrace();
			fail();
		}
		config.setApplicationDataSource(ads);		
		qm.setup(config);
	}
	
	public void testInsertEmailQueue(){
		EmailMessage email = new EmailMessage();
		email.setFrom("echamussy@yahoo.com");
		email.setBody("The body");
		email.setFromName("Enrique");
		email.setSubject("The subject");
		email.setTo(new String[]{"enrique.rodriguez@vw.com; enrique.rodriguez@gedas.com"});
		email.setToName(new String[]{"Enrique VW", "Enrique Gedas"});
		try {
			qm.addEmailToQueue(email);
		} catch (XpressoException e) {
			e.getTheException().printStackTrace();
			fail();
		}
	}

	public void testRunEmailQueue(){
		QueueCommand command = new QueueCommand();
		command.setCommand("SELECT * FROM emq_email_queue LIMIT 1,1");
		
		EmailConfiguration conf = new EmailConfiguration();
		conf.setHost("mail.erclab.com");
		conf.setUser("me@erclab.com");
		conf.setPass("themail9");
		conf.setAuthentication(true);
		
		command.setEmailConfiguration(conf);
		try {
			qm.runQueue(command);
		} catch (XpressoException e) {
			e.getTheException().printStackTrace();
			fail();
		}
	}
	
}
